<template>
    <div class="page">
        <h2 class="title">修改通用合同</h2>

        <!-- 表单区域 -->
        <div class="form-container">
            <form @submit.prevent="() => submit('approval')">
                <!-- 两列布局 -->
                <div class="form-grid">
                    <!-- 左列 -->
                    <div class="form-column">
                        <!-- 合同编号 -->
                        <div class="form-item">
                            <label>合同编号:</label>
                            <input type="text" v-model="form.contractNumber" placeholder="合同编号" readonly
                                style="background-color: #f5f5f5;" />
                        </div>

                        <!-- 合同标题 -->
                        <div class="form-item required">
                            <label>*合同标题:</label>
                            <input type="text" v-model="form.contractTitle" placeholder="请输入合同标题" required />
                        </div>

                        <!-- 合同类别 -->
                        <div class="form-item required">
                            <label>*合同类别:</label>
                            <input type="text" v-model="form.contractCategory" placeholder="请输入合同类别" required />
                        </div>

                        <!-- 签订时间 -->
                        <div class="form-item required">
                            <label>*签订时间:</label>
                            <input type="date" v-model="form.signingDate" placeholder="请选择签订时间" required />
                        </div>

                        <!-- 合同金额 -->
                        <div class="form-item">
                            <label>合同金额:</label>
                            <input type="number" v-model="form.contractAmount" placeholder="请输入合同金额" step="0.01" />
                        </div>
                    </div>

                    <!-- 右列 -->
                    <div class="form-column">
                        <!-- 对方单位（下拉，选择后联动负责人） -->
                        <div class="form-item required">
                            <label>*对方单位:</label>
                            <select v-model.number="form.unitId" @change="onUnitChange">
                                <option value="">请选择对方单位</option>
                                <option v-for="u in unitOptions" :key="u.id" :value="u.id">{{ u.name }}</option>
                            </select>
                        </div>

                        <!-- 对方负责人（下拉） -->
                        <div class="form-item required">
                            <label>*对方负责人:</label>
                            <select v-model="form.ownerName">
                                <option value="">请选择对方负责人</option>
                                <option v-for="o in ownerOptions" :key="o" :value="o">{{ o }}</option>
                            </select>
                        </div>



                        <!-- 经办人 -->
                        <div class="form-item required">
                            <label>*经办人:</label>
                            <input type="text" v-model="form.handler" placeholder="请输入经办人" required />
                        </div>
                    </div>
                </div>

                <!-- 文本区域 -->
                <div class="form-section">
                    <!-- 合同标的或项目说明 -->
                    <div class="form-item">
                        <label>合同标的或项目说明:</label>
                        <textarea v-model="form.contractSubjectDescription" placeholder="请输入合同标的或项目说明"
                            rows="4"></textarea>
                    </div>

                    <!-- 合同主要条款/变更条款 -->
                    <div class="form-item">
                        <label>合同主要条款/变更条款:</label>
                        <textarea v-model="form.contractTerms" placeholder="请输入合同主要条款/变更条款" rows="4"></textarea>
                    </div>
                </div>

                <!-- 文件上传区域 -->
                <div class="form-section">
                    <div class="form-item">
                        <label>合同文本(附件):</label>
                        <div class="file-upload">
                            <input type="file" ref="fileInput" @change="onFileChange"
                                accept=".pdf,.doc,.docx,.xls,.xlsx,.txt" style="display: none" />
                            <button type="button" class="btn primary" @click="fileInput?.click()">
                                选取文件
                            </button>
                            <span class="file-info" v-if="selectedFile">
                                {{ selectedFile.name }}
                            </span>
                            <span class="file-info" v-else-if="form.contractAttachment">
                                当前附件: {{ form.contractAttachment }}
                            </span>
                        </div>
                        <div class="file-tip">
                            (单个附件最大支持20M,支持:PDF、Word、Excel、Txt格式)
                        </div>
                    </div>
                </div>

                <!-- 按钮区域 -->
                <div class="form-actions">
                    <button type="button" class="btn primary" @click="submit('approval')">
                        提交审批
                    </button>
                    <button type="button" class="btn" @click="cancel">
                        取消
                    </button>
                    <button type="button" class="btn primary" @click="submit('draft')">
                        保存草稿
                    </button>
                </div>
            </form>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useCounterStore } from '@/stores/counter'
import { read, write } from '@/assets/Axios/axiosHttple'

const router = useRouter()
const route = useRoute()
const counts = useCounterStore()

// 表单数据模型
const form = reactive({
    id: 0,
    contractNumber: '',
    contractTitle: '',
    unitId: 0,
    ownerName: '',
    // 可选的货主ID，用于联查货主管理并填充对方单位/负责人
    cargoOwnerId: 0,
    counterpartyUnit: '', // 对方单位
    contractCategory: '',
    signingDate: '',
    handler: '',
    contractAmount: 0,
    contractSubjectDescription: '',
    contractTerms: '',
    contractAttachment: '',
    createDate: '',
    processDetail: 0,
    lastModifiedBy: ''
})

// 文件上传相关
const fileInput = ref<HTMLInputElement>()
const selectedFile = ref<File | null>(null)
const loading = ref(false)

// 对方单位与负责人下拉选项（用于与货主管理联查后填充）
const counterpartyOptions = ref<string[]>([])
const ownerOptions = ref<string[]>([])

// 承运/单位下拉的通用类型及数据（与 CarriageContracts 保持一致）
type Option = { id: number; name: string; normalized?: string }
const unitOptions = ref<Option[]>([])

// 加载单位下拉（调用 External 接口，和承运合同页一致）
async function loadUnits() {
    try {
        const res = await read.get('baseinforead/api/External/GetExternalList', { params: { PageIndex: 1, PageSize: 999 } })
        const j: any = res?.data ?? {}
        const dataBlock = j?.data || j
        const list = Array.isArray(dataBlock) ? dataBlock : (Array.isArray(dataBlock?.data) ? dataBlock.data : [])

        unitOptions.value = list.map((x: any) => {
            const name = x.UnitName ?? x.unitName ?? x.Name ?? x.name ?? x.CompanyName ?? x.companyName ?? ''
            const normalized = String(name || '').replace(/\s+/g, '').replace(/[\-_,.·•()（）]/g, '').toLowerCase()
            return { id: Number(x.Id ?? x.id ?? x.UnitId ?? x.unitId), name, normalized }
        }).filter((x: any) => Number.isFinite(x.id) && x.name)
    } catch (error) {
        // ignore
    }
}

// 选择单位后联动加载货主（负责人）
async function onUnitChange() {
    if (form.unitId && Number.isFinite(form.unitId)) {
        const selectedUnit = unitOptions.value.find(u => u.id === Number(form.unitId))
        if (selectedUnit && selectedUnit.name) form.counterpartyUnit = selectedUnit.name
        await fetchCargoOwnerByUnitId(Number(form.unitId))
    } else {
        ownerOptions.value = []
        form.ownerName = ''
    }
}

// 根据单位ID在货主列表中查找对应负责人（复用承运合同的逻辑）
async function fetchCargoOwnerByUnitId(unitId: number) {
    try {
        const res = await read.get('baseinforead/api/CargoOwner/GetCargoOwnerList', { params: { PageIndex: 1, PageSize: 999 } })
        const j: any = res?.data ?? {}
        const dataBlock = j?.data || j
        const list = Array.isArray(dataBlock) ? dataBlock : (Array.isArray(dataBlock?.data) ? dataBlock.data : [])

        const toNumber = (v: any) => { const n = Number(v); return Number.isFinite(n) ? n : NaN }
        let matchedCargoOwners = list.filter((item: any) => {
            const itemUnitId = toNumber(item.UnitId ?? item.unitId ?? item.Id ?? item.id)
            return !Number.isNaN(itemUnitId) && itemUnitId === unitId
        })

        if (matchedCargoOwners.length === 0) {
            const selectedUnit = unitOptions.value.find(u => u.id === unitId)
            const unitNormalized = selectedUnit?.normalized || selectedUnit?.name?.replace(/\s+/g, '').replace(/[\-_,.·•()（）]/g, '').toLowerCase()
            if (unitNormalized) {
                matchedCargoOwners = list.filter((item: any) => {
                    const names = [item.UnitName, item.unitName, item.CompanyName, item.companyName, item.Name, item.name]
                    return names.some((n: any) => typeof n === 'string' && n.replace(/\s+/g, '').replace(/[\-_,.·•()（）]/g, '').toLowerCase().includes(unitNormalized))
                })
            }
        }

        if (matchedCargoOwners.length > 0) {
            const ownerNames = matchedCargoOwners.map((item: any) => {
                return item.ownerName ?? item.OwnerName ?? item.Contact ?? item.contact ?? item.Principal ?? item.principal ?? item.Name ?? item.name
            }).filter(Boolean) as string[]

            if (ownerNames.length > 0) {
                ownerOptions.value = [...new Set(ownerNames)]
                if (ownerOptions.value.length === 1) form.ownerName = ownerOptions.value[0]
                else form.ownerName = ''
            } else {
                ownerOptions.value = []
                form.ownerName = ''
            }
        } else {
            ownerOptions.value = []
            form.ownerName = ''
        }
    } catch (error) {
        console.error('[fetchCargoOwnerByUnitId] error', error)
        ownerOptions.value = []
        form.ownerName = ''
    }
}

// 文件选择处理
function onFileChange(event: Event) {
    const target = event.target as HTMLInputElement
    if (target.files && target.files.length > 0) {
        selectedFile.value = target.files[0]
        form.contractAttachment = selectedFile.value.name
    }
}

// 加载合同详情
async function loadDetail() {
    const id = route.query.id
    if (!id) {
        alert('缺少合同ID参数')
        router.push('/GetGeneralContracts')
        return
    }

    loading.value = true
    try {
        // 调用详情API获取合同信息
        const url = `contractmanagementread/api/ContractManagementControllers/GetGeneralById/General/${id}`
        const res = await read.get(url)
        const result = res?.data ?? {}

        if ((res?.status === 200) && result.code === 200 && result.data) {
            const data = result.data
            // 映射数据到表单
            form.id = data.Id || data.id || 0
            form.contractNumber = data.ContractNumber || data.contractNumber || ''
            form.contractTitle = data.ContractTitle || data.contractTitle || ''
            form.unitId = data.UnitId || data.unitId || 0
            form.ownerName = data.OwnerName || data.ownerName || ''
            form.counterpartyUnit = data.CounterpartyUnit || data.counterpartyUnit || ''
            form.contractCategory = data.ContractCategory || data.contractCategory || ''
            form.signingDate = data.SigningDate ? new Date(data.SigningDate).toISOString().split('T')[0] : ''
            form.handler = data.Handler || data.handler || ''
            form.contractAmount = data.ContractAmount || data.contractAmount || 0
            form.contractSubjectDescription = data.ContractSubjectDescription || data.contractSubjectDescription || ''
            form.contractTerms = data.ContractTerms || data.contractTerms || ''
            form.contractAttachment = data.ContractAttachment || data.contractAttachment || ''
            form.createDate = data.CreateDate || data.createDate || ''
            form.processDetail = data.ProcessDetail || data.processDetail || 0
            // 如果后端返回货主ID，尝试联查货主管理接口填充对方单位/负责人
            const coid = data.CargoOwnerId ?? data.cargoOwnerId ?? data.CargoOwnerID ?? data.cargoOwnerID ?? data.OwnerId ?? data.ownerId ?? data.CargoOwner ?? data.cargoOwner
            if (coid) {
                const n = Number(coid)
                if (!Number.isNaN(n) && n > 0) fetchCargoOwnerById(n)
            }
        } else {
            alert(result.message || '获取合同详情失败')
            router.push('/GetGeneralContracts')
        }
    } catch (error) {
        console.error('加载详情失败:', error)
        alert('加载合同详情失败，请重试')
        router.push('/GetGeneralContracts')
    } finally {
        loading.value = false
    }
}

// 通过货主ID从后端获取货主信息并填充对方单位与负责人（与 Add 页面实现一致）
async function fetchCargoOwnerById(id: number) {
    try {
        const res = await read.get(`baseinforead/api/CargoOwner/GetCargoOwnerById/${encodeURIComponent(String(id))}`)
        if (!res?.status || res.status !== 200) return
        const d = res.data?.data ?? res.data
        if (!d) return

        form.cargoOwnerId = id
        form.counterpartyUnit = d.UnitName ?? d.unitName ?? d.CompanyName ?? d.companyName ?? d.Name ?? d.name ?? form.counterpartyUnit
        form.ownerName = d.OwnerName ?? d.ownerName ?? d.Contact ?? d.contact ?? d.Principal ?? d.principal ?? form.ownerName
    } catch (e) {
        console.error('[fetchCargoOwnerById] error', e)
    }
}

function promptAndFetchCargoOwner() {
    const idStr = prompt('请输入货主ID以联查货主管理（仅数字）')
    if (!idStr) return
    const id = Number(idStr)
    if (Number.isNaN(id)) { alert('货主ID格式不正确'); return }
    fetchCargoOwnerById(id)
}

// 表单验证
function validate() {
    if (!form.contractTitle.trim()) {
        alert('请输入合同标题')
        return false
    }
    if (!form.ownerName.trim()) {
        alert('请输入对方负责人')
        return false
    }
    if (!form.signingDate) {
        alert('请选择签订时间')
        return false
    }
    if (!form.counterpartyUnit.trim()) {
        alert('请输入对方单位')
        return false
    }
    if (!form.contractCategory.trim()) {
        alert('请输入合同类别')
        return false
    }
    if (!form.handler.trim()) {
        alert('请输入经办人')
        return false
    }
    return true
}

// 提交表单
async function submit(mode: 'approval' | 'draft') {
    if (!validate()) return

    try {
        // 构建后端期望的请求体（与接口示例保持一致）
        const submitData = {
            id: form.id,
            contractNumber: form.contractNumber,
            contractTitle: form.contractTitle,
            unitId: form.unitId,
            ownerName: form.ownerName,
            contractCategory: form.contractCategory,
            signingDate: form.signingDate ? new Date(form.signingDate).toISOString() : new Date().toISOString(),
            handler: form.handler,
            contractAmount: Number(form.contractAmount) || 0,
            contractSubjectDescription: form.contractSubjectDescription,
            contractTerms: form.contractTerms,
            contractAttachment: form.contractAttachment,
            // 如果后端使用 createDate 字段，优先传表单里的值，否则使用当前时间
            createDate: form.createDate || new Date().toISOString(),
            processDetail: mode === 'approval' ? 1 : 0,
            // lastModifiedBy：若表单没有填写则使用当前登录用户 id/名称（转为字符串）
            lastModifiedBy: String(form.lastModifiedBy ?? counts.Logins.UserId ?? counts.Logins.Nickname ?? counts.Logins.Account ?? ''),
        }

        const candidates = [
            `contractmanagementwrite/api/ContractManagement/UpdateGeneral/general/update/${encodeURIComponent(String(form.id || submitData.id || ''))}`,
            'contractmanagementwrite/api/ContractManagement/UpdateGeneral/general/update',
            'contractmanagementwrite/api/ContractManagement/Update/update'
        ]
        let lastErr: any = null
        for (const u of candidates) {
            try {
                const resp = await write.post(u, submitData)
                const r: any = resp?.data ?? {}
                if (resp.status === 200 && (Number(r?.code) === 200 || r?.ok === true)) {
                    const message = mode === 'approval' ? '提交审批成功' : '保存草稿成功'
                    alert(message)
                    router.push('/GetGeneralContracts?refresh=1')
                    return
                }
                lastErr = { status: resp?.status, body: r }
            } catch (e) { lastErr = e }
        }
        console.error('[UpdateGeneral submit] last error=', lastErr)
        alert(lastErr?.body?.message || lastErr?.message || '提交失败')
    } catch (error) {
        console.error('提交失败:', error)
        alert('提交失败，请重试')
    }
}

// 取消操作
function cancel() {
    router.push('/GetGeneralContracts')
}

// 组件挂载时初始化
onMounted(() => {
    // 设置修改人为当前登录用户（从 pinia store 中读取登录信息）
    form.lastModifiedBy = counts.Logins.Nickname || counts.Logins.Account || counts.Logins.UserId || ''

    // 并行加载单位下拉，随后加载详情以确保 unitOptions 可用于匹配
    Promise.all([loadUnits()]).then(() => loadDetail()).catch(() => loadDetail())
})
</script>

<style scoped>
.page {
    padding: 16px;
    max-width: 1200px;
    margin: 0 auto;
}

.title {
    margin: 8px 0 20px;
    font-size: 18px;
    font-weight: bold;
    color: #333;
}

.form-container {
    background: #fff;
    border-radius: 8px;
    padding: 24px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.form-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 24px;
    margin-bottom: 24px;
}

.form-column {
    display: flex;
    flex-direction: column;
    gap: 16px;
}

.form-section {
    margin-bottom: 24px;
}

.form-item {
    display: flex;
    flex-direction: column;
    gap: 6px;
}

.form-item.required label::before {
    content: '*';
    color: #ff4d4f;
    margin-right: 4px;
}

.form-item label {
    font-weight: 500;
    color: #333;
    font-size: 14px;
}

.form-item input,
.form-item textarea,
.form-item select {
    padding: 8px 12px;
    border: 1px solid #d9d9d9;
    border-radius: 6px;
    font-size: 14px;
    transition: border-color 0.3s;
}

.form-item input:focus,
.form-item textarea:focus,
.form-item select:focus {
    outline: none;
    border-color: #1677ff;
    box-shadow: 0 0 0 2px rgba(22, 119, 255, 0.2);
}

.form-item textarea {
    resize: vertical;
    min-height: 80px;
}

.file-upload {
    display: flex;
    align-items: center;
    gap: 12px;
}

.file-info {
    color: #666;
    font-size: 14px;
}

.file-tip {
    color: #999;
    font-size: 12px;
    margin-top: 4px;
}

.form-actions {
    display: flex;
    gap: 12px;
    justify-content: center;
    margin-top: 32px;
    padding-top: 24px;
    border-top: 1px solid #f0f0f0;
}

.btn {
    padding: 8px 24px;
    border: 1px solid #d9d9d9;
    border-radius: 6px;
    background: #fff;
    color: #333;
    font-size: 14px;
    cursor: pointer;
    transition: all 0.3s;
}

.btn:hover {
    border-color: #1677ff;
    color: #1677ff;
}

.btn.primary {
    background: #1677ff;
    color: #fff;
    border-color: #1677ff;
}

.btn.primary:hover {
    background: #4096ff;
    border-color: #4096ff;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .form-grid {
        grid-template-columns: 1fr;
        gap: 16px;
    }

    .form-actions {
        flex-direction: column;
    }

    .btn {
        width: 100%;
    }
}
</style>
